package com.df.handler;

import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.client.task.ExternalTask;
import org.camunda.bpm.client.task.ExternalTaskService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

//@Component
@Slf4j
public class SqlInjectHandler {
    
    private final ExternalTaskClient client;
    
    public SqlInjectHandler(ExternalTaskClient client) {
        this.client = client;
    }
    
    @PostConstruct
    public void subscribe() {
        client.subscribe("sql-inject-topic")
            .handler(this::handleSqlInject)
            .open();
        
        log.info("订阅 sql-inject-topic 成功");
    }
    
    private void handleSqlInject(ExternalTask externalTask, ExternalTaskService externalTaskService) {
        try {
            log.info("开始处理SQL注入检测任务，任务ID: {}", externalTask.getId());
            
            // 获取流程变量
            String processInstanceId = externalTask.getProcessInstanceId();
            Object processDataResult = externalTask.getVariable("processDataResult");
            log.info("流程实例ID: {}, 数据处理结果: {}", processInstanceId, processDataResult);
            
            // 模拟SQL注入检测逻辑
            log.info("执行SQL注入检测...");
            Thread.sleep(1000); // 模拟检测时间
            
            // 模拟检测结果（随机成功或失败）
            Random random = new Random();
            boolean sqlInjectResult = random.nextBoolean();
            
            // 设置输出变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("sqlInjectResult", sqlInjectResult);
            variables.put("sqlInjectTime", System.currentTimeMillis());
            variables.put("sqlInjectDetails", sqlInjectResult ? "未检测到SQL注入" : "检测到SQL注入风险");
            
            // 完成任务
            externalTaskService.complete(externalTask, variables);
            
            log.info("SQL注入检测任务完成，任务ID: {}, 结果: {}", externalTask.getId(), sqlInjectResult);
            
        } catch (Exception e) {
            log.error("处理SQL注入检测任务失败，任务ID: {}", externalTask.getId(), e);
            
            // 处理失败
            externalTaskService.handleBpmnError(externalTask, "SQL_INJECT_ERROR", "SQL注入检测失败: " + e.getMessage());
        }
    }
} 